package core.tool.bpe.action;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;

import core.tool.bpe.Action;
import core.tool.bpe.BpeContext;
import core.tool.io.FileHelper;
import core.tool.xml.dom4j.jaxb.XmlHelper;

public class ReplaceAction extends Action {

	@Override
	protected boolean execute(BpeContext bpeContext) {
		List<ReplaceBean> replaceList=new ArrayList<ReplaceBean>();
		List<Element> list=XmlHelper.selectSingleElements(bpeContext.getElement(), "<ReplaceFiles>/ReplaceFile");
		for(Element replaceElement:list) {
			String soureDir=XmlHelper.getElementAttribute(replaceElement, "sourceDir");
			ReplaceBean replaceBean=new ReplaceBean(soureDir);
			List<Element> items=XmlHelper.selectSingleElements(bpeContext.getElement(), "<ReplaceItems>/ReplaceItem");
			for(Element item:items) {
				String beforeReplace=XmlHelper.getElementAttribute(item, "beforeReplace");
				String afterReplace=XmlHelper.getElementAttribute(item, "afterReplace");;
				ReplaceItemBean replaceItemBen=new ReplaceItemBean(beforeReplace,afterReplace);
				replaceBean.addReplaceItem(replaceItemBen);
			}
			replaceList.add(replaceBean);
			try {
				FileHelper.replaceFile(replaceBean);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

}
